package collector.app.nexd.com.singlecollection.activity;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.transition.Fade;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dd.morphingbutton.MorphingAnimation;
import com.dd.morphingbutton.MorphingButton;

import collector.app.nexd.com.singlecollection.R;
import collector.app.nexd.com.singlecollection.adapter.EmailAdapter;
import collector.app.nexd.com.singlecollection.presenter.signin.SignInContract;
import collector.app.nexd.com.singlecollection.presenter.signin.SignInPresenter;
import collector.app.nexd.com.singlecollection.util.ProgressUtil;
import collector.app.nexd.com.singlecollection.widget.AutoEmailEditText;

public class SignInActivity extends AppCompatActivity implements View.OnClickListener, SignInContract.View, TextWatcher {
    private MorphingButton btnLogin;
    private RelativeLayout rlLayout;
    private AutoEmailEditText emailEditText;
    private EditText pwdEdit;
    //邮箱验证成功按钮的长度
    private int emailSuccessWidth;
    private int emailSuccessHeight;
    private SignInContract.Presenter signInPresenter;
    private MorphingButton.Params params;
    public static final String VALIDATE_OK = "success";
    public static final String VALIDATE_FAIL = "fail";
    private boolean signStatus = false;
    private ProgressDialog progressDialog;
    private TextView tvDownload;
    private CheckBox ckrRem;
    public static final String EXTRA_NAME = "userName";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        setContentView(R.layout.activity_login);
        signInPresenter = new SignInPresenter(this);
        initView();
        initData();
        initExitAnim();
    }

    private void initData() {
        signInPresenter.init();
        emailEditText.setAdapter(new EmailAdapter(this, null, true));
    }


    @Override
    public void showToast(String msg) {
        Toast.makeText(SignInActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void startActivity() {
    }

    @Override
    public void printLog(String msg) {

    }

    private void initExitAnim() {
        setupExitAnimation();
    }

    // 退出动画
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setupExitAnimation() {
        Fade fade = new Fade();
        getWindow().setSharedElementReturnTransition(fade);
        fade.setDuration(300);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signInPresenter.signIn(emailEditText.getText().toString().trim(), pwdEdit.getText().toString().trim());
                break;
            case R.id.login_tv_download:
                signInPresenter.loadUserInfo();
                break;
            case R.id.login_ck_rem:
                if (!TextUtils.isEmpty(emailEditText.getText().toString())) {
                    signInPresenter.isRemember(emailEditText.getText().toString().trim(), ckrRem.isChecked());
                }
                break;
        }
    }

    @Override
    public void initView() {
        btnLogin = (MorphingButton) findViewById(R.id.sign_in_button);
        rlLayout = (RelativeLayout) findViewById(R.id.login_rl_container);
        emailEditText = (AutoEmailEditText) findViewById(R.id.login_edit_email);
        tvDownload = (TextView) findViewById(R.id.login_tv_download);
        ckrRem = (CheckBox) findViewById(R.id.login_ck_rem);
        pwdEdit = (EditText) findViewById(R.id.login_edit_pwd);
        progressDialog = ProgressUtil.createProgressDialog(this);
        rlLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rlLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                emailSuccessWidth = rlLayout.getMeasuredWidth() - 100;
                emailSuccessHeight = btnLogin.getMeasuredHeight();
            }
        });
        localValidateFail(0);
        emailEditText.addTextChangedListener(this);
        pwdEdit.addTextChangedListener(this);
        btnLogin.setOnClickListener(this);
        ckrRem.setOnClickListener(this);
        tvDownload.setOnClickListener(this);

    }


    @Override
    public void initIsRem(String email) {
        emailEditText.setText(email);
        pwdEdit.requestFocus();
    }

    @Override
    public void loading() {
        progressDialog.show();
    }

    @Override
    public void loadDataSuccess() {
        showToast(getString(R.string.data_request_ok));
        ckrRem.setChecked(false);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    public void loadDataFail() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    public void signInSuccess(final String userName) {
        params = MorphingButton.Params.create()
                .duration(getResources().getInteger(R.integer.mb_animation))
                .cornerRadius((int) getResources().getDimension(R.dimen.mb_height_56))
                .width((int) getResources().getDimension(R.dimen.mb_height_56))
                .height((int) getResources().getDimension(R.dimen.mb_height_56))
                .color(ContextCompat.getColor(this, R.color.inner_circle_color))
                .icon(R.drawable.ic_done).animationListener(new MorphingAnimation.Listener() {
                    @Override
                    public void onAnimationEnd() {
                        Intent intent = new Intent(SignInActivity.this, SettingActivity.class);
                        intent.putExtra(EXTRA_NAME, userName);
                        startActivity(intent);
                        finish();
                    }
                });
        btnLogin.morph(params);

    }

    @Override
    public void signInUserNameFail() {
        emailEditText.requestFocus();
        emailEditText.setError("用户不存在");
    }

    @Override
    public void signInPwdFail() {
        pwdEdit.requestFocus();
        pwdEdit.setError("用户密码错误");
    }


    @Override
    public void rememberError() {
        emailEditText.setError("该用户不存在");
        emailEditText.requestFocus();
        ckrRem.setChecked(false);
    }


    public void localValidateSuccess() {
        MorphingButton.Params signInParam = MorphingButton.Params.create();
        signInParam.color(ContextCompat.getColor(this, R.color.inner_circle_color)).cornerRadius(10).width(emailSuccessWidth).height(emailSuccessHeight).strokeWidth(0).text(getString(R.string.action_sign_in_next)).duration(getResources().getInteger(R.integer.mb_animation));
        btnLogin.morph(signInParam);
        btnLogin.setTag("success");
        btnLogin.setTextColor(ContextCompat.getColor(this, android.R.color.white));
        btnLogin.setEnabled(true);
    }

    public void localValidateFail(int duration) {
        params = MorphingButton.Params.create();
        params.color(ContextCompat.getColor(this, android.R.color.transparent)).cornerRadius(20).width(400).height(emailSuccessHeight).strokeColor(R.color.line_bg).strokeWidth(2).text("下一步").duration(duration);
        btnLogin.morph(params);
        btnLogin.setTextColor(ContextCompat.getColor(this, R.color.line_bg));
        btnLogin.setEnabled(false);
        btnLogin.setTag("fail");
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String email = "";
        String pwd = "";
        if (getCurrentFocus() == null) {
            return;
        } else {
            switch (getCurrentFocus().getId()) {
                case R.id.login_edit_email:
                    email = s.toString();
                    pwd = pwdEdit.getText().toString();
                    break;
                case R.id.login_edit_pwd:
                    email = emailEditText.getText().toString();
                    pwd = s.toString();
                    break;
            }
            signStatus = signInPresenter.checkUser(email, pwd);

            if (btnLogin.getTag() == VALIDATE_FAIL) {
                if (signStatus) {
                    localValidateSuccess();
                }
            }
            if (btnLogin.getTag() == VALIDATE_OK) {
                if (!signStatus) {
                    localValidateFail(getResources().getInteger(R.integer.mb_animation));
                }
            }
        }

    }
}
